package com.recorder.recorder_lib;

import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.MediaPlayer;

import com.recorder.recorder_lib.core.IRecordingManager;
import com.recorder.recorder_lib.core.RecordingService;
import com.recorder.recorder_lib.utils.FileManager;

/**
 * desc   : 录音管理器
 * time   : 2018年12月21日15 : 24
 */
public class RecordingManager implements IRecordingManager {
    private ServiceConnection mServiceConnection;

    public RecordingManager(String dirName, ServiceConnection serviceConnection) {
        mServiceConnection = serviceConnection;
        FileManager.setDirPath(dirName);
        FileManager.init();
    }

    @Override
    public void startRecord(Context context) {
        context.bindService(new Intent(context, RecordingService.class), mServiceConnection, Context.BIND_AUTO_CREATE);

    }

    @Override
    public void endRecord(Context context) {
        context.unbindService(mServiceConnection);
    }

    @Override
    public void pauseRecord() {

    }

    @Override
    public void resumeRecord() {

    }

    private MediaPlayer mMediaPlayer;

    @Override
    public void playSound(String url) {
        if (mMediaPlayer != null) {
            stopSound();
        }
        mMediaPlayer = new MediaPlayer();
        try {
            mMediaPlayer.setDataSource(url);
            mMediaPlayer.prepareAsync();
            mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mMediaPlayer.start();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void stopSound() {
        if (mMediaPlayer == null)
            return;
        try {
            mMediaPlayer.stop();
            mMediaPlayer.release();
            mMediaPlayer = null;
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void saveFile() {

    }

    @Override
    public void deleteFile() {

    }

    @Override
    public void searchFile() {

    }


}